const { app, BrowserWindow, Tray, Menu, ipcMain, session, dialog } = require('electron');
const { exec } = require('child_process');
let fs = require("fs")
const path = require('path');
const { kill } = require('process');
const si = require('systeminformation');
let mainWindow;
let tray;
let HMC = require("hmc-win32");
const { Console } = require('console');
const CRYPTO = require("../common/crypto")
const moment = require('moment');
// 避免Electron Security Warning (Disabled webSecurity)
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
// 设置缓存目录
app.setPath('userData', path.join(__dirname, "/temp"))

// 获取设备id
async function getDeviceId() {
    return new Promise((resolve, reject) => {
        si.system()
            .then(systemInfo => {
                const deviceId = systemInfo.uuid;
                resolve(deviceId);
            })
            .catch(error => {
                reject(error);
            });
    });
}
// 读取授权文件



function killPort(port) {
    let pid = [];
    exec(`netstat -ano|findstr "${port}"`, (beforeErr, out, afterErr) => {
        console.log(1, beforeErr);
        console.log(2, out);
        console.log(3, afterErr);

        if (out) {
            let line = out.split("\r\n");
            for (let i = 0; i < line.length; i++) {
                line[i] = line[i].replaceAll(/\s+/g, '-');
                let spices = line[i].split("-");
                pid.push(spices[spices.length - 1]);
            }
            pid = [...new Set(pid)];
            console.log(pid);
            for (let i = 0; i < pid.length; i++) {
                exec(`taskkill /pid ${pid[i]} /f`, (a, b, c) => { })
            }
        }
    })
}

function findPort(port, webContents) {
    let pid = [];
    exec(`netstat -ano|findstr "${port}"`, (beforeErr, out, afterErr) => {
        console.log(1, beforeErr);
        console.log(2, out);
        console.log(3, afterErr);

        if (out) {
            let line = out.split("\r\n");
            for (let i = 0; i < line.length; i++) {
                line[i] = line[i].replaceAll(/\s+/g, '-');
                let spices = line[i].split("-");
                pid.push(spices[spices.length - 1]);
            }
            pid = [...new Set(pid)];
        }
        webContents.send("port-pids", {
            port: port,
            pids: pid
        });
    })
}


function killPort(port) {
    let pid = [];
    exec(`netstat -ano|findstr "${port}"`, (beforeErr, out, afterErr) => {
        console.log(1, beforeErr);
        console.log(2, out);
        console.log(3, afterErr);

        if (out) {
            let line = out.split("\r\n");
            for (let i = 0; i < line.length; i++) {
                line[i] = line[i].replaceAll(/\s+/g, '-');
                let spices = line[i].split("-");
                pid.push(spices[spices.length - 1]);
            }
            pid = [...new Set(pid)];
            console.log(pid);
            for (let i = 0; i < pid.length; i++) {
                exec(`taskkill /pid ${pid[i]} /f`, (a, b, c) => { })
            }
        }
    })
}

function
    closeProcess(name) {
    let pid = [];
    exec(`tasklist | findstr "${name}"`, (beforeErr, out, afterErr) => {
        console.log(1, beforeErr);
        console.log(2, out);
        console.log(3, afterErr);

        if (out) {
            let line = out.split("\r\n");
            for (let i = 0; i < line.length; i++) {
                line[i] = line[i].replaceAll(/\s+/g, '-');
                let spices = line[i].split("-");
                pid.push(spices[1]);
            }
            pid = [...new Set(pid)];
            console.log(pid);
            for (let i = 0; i < pid.length; i++) {
                exec(`taskkill /pid ${pid[i]} /f`, (a, b, c) => { })
            }
        }
    })


}

let selectProcess = false;

// 创建主窗口
function createWindow() {
    mainWindow = new BrowserWindow({
        width: 580,
        height: 370,
        show: true,
        resizable: false,
        frame: true, // 隐藏窗口边框
        alwaysOnTop: true, // 将窗口设置为始终在顶部
        webPreferences: {
            webSecurity: false,
            nodeIntegration: true,
            devTools: true,
            sandbox: false,
            contextIsolation: true,
            preload: path.join(__dirname, '../preload/preload.js'),
        },
        icon: path.join(__dirname, '../assets/cmd.png')
    });

    // // 监听窗口失焦事件
    // mainWindow.on('blur', () => {
    //     mainWindow.hide(); // 窗口失焦时隐藏窗口
    // });

    // 隐藏操作栏
    mainWindow.setMenu(null);

    // 加载应用的主页面
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));

    // 隐藏任务栏图标
    mainWindow.setSkipTaskbar(true);

    // 创建系统托盘图标
    tray = new Tray(path.join(__dirname, '../assets/cmd.png'));

    // 设置鼠标悬停时的提示文本
    tray.setToolTip('CmdTool');
    const contextMenu = Menu.buildFromTemplate([
        // { label: '消息', type: 'normal', click: () => console.log('点击了菜单项1') },
        // {
        //     label: '测试', type: 'normal', click: () => {
        //         let ports = [9876, 8123];
        //         for (let i = 0; i < ports.length; i++) {
        //             killPort(ports[i]);
        //         }
        //         // killPort(9876);
        //     }
        // },
        // { type: 'separator' },
        { label: '退出', type: 'normal', click: () => app.quit() }
    ]);

    tray.on("click", () => {
        mainWindow.show();
    })

    tray.setContextMenu(contextMenu);

    // 监听来自渲染进程的消息
    ipcMain.on('kill-port', (event, newValue) => {
        console.log("kill-port", newValue);
        killPort(newValue);
    });

    // 监听来自渲染进程的消息
    ipcMain.on('find-port', (event, newValue) => {
        console.log("find-port", newValue);
        findPort(newValue, mainWindow.webContents);
    });

    ipcMain.on('exec-cmd', (event, newValue) => {
        console.log("exec-cmd", newValue);
        // 填充参数
        let cmd = JSON.parse(newValue);
        let count = cmd.count ? cmd.count : 1;
        console.log("exec-count", count);
        let oriCmd = cmd.cmd;
        console.log("ori-cmd", oriCmd);
        newValue = "";
        let index = 0;
        for (i in oriCmd) {
            if (oriCmd[i] != "?") {
                newValue += oriCmd[i];
            } else {
                newValue += cmd.args[index].value;
                index++;
            }
        }
        console.log("last-cmd", newValue);

        let cmds = [];
        if (newValue.includes(";")) {
            cmds = newValue.split(";");
        } else {
            cmds.push(newValue);
        }

        for (let j = 0; j < count; j++) {

            for (let i = 0; i < cmds.length; i++) {
                console.log("exec-cmd: ", cmds[i]);
                console.log("==================");
                exec(cmds[i], (beforeErr, out, afterErr) => {
                    console.log(1, beforeErr);
                    console.log(2, out);
                    console.log(3, afterErr);
                    let before = beforeErr != null && beforeErr != '';
                    let after = afterErr != null && afterErr != '';
                    if (before) {
                        mainWindow.webContents.send('error', "exec error");
                    }
                    if (after) {
                        mainWindow.webContents.send('error', "exec error");
                    }
                    if (!before && !after) {
                        mainWindow.webContents.send('info', "exec success");
                    }
                })
            }
        }

    });

    ipcMain.on('update-cmd', (event, newValue) => {
        console.log("update-cmd: ", newValue);
        fs.writeFileSync(path.join(process.cwd(), 'command.txt'), newValue);
    });


    // 监听来自渲染进程的消息
    ipcMain.on('close-process', (event, newValue) => {
        console.log("close-process", newValue);
        closeProcess(newValue);
    });

    ipcMain.on('cancelGetProcessName', () => {
        selectProcess = false;
    });
    ipcMain.on('getProcessName', () => {
        selectProcess = true;
    });

    HMC.Auto.mouseHook.on("mouse", function (env) {
        // let HWND = HMC.getPointWindowMain().HWND;
        // let { x, y, width, height } = HMC.getWindowRect(HWND);
        //console.log(HMC.getWindowRect(HWND));
        // console.log(HMC.getWindowRect(HWND));
        if (env.event == "left-button-down") {
            if (selectProcess) {
                selectProcess = false;
                // HMC.captureBmpToFile(path.join(process.cwd() + "1123.jpg"), x, y, width, height);
                mainWindow.webContents.send("processName", HMC.getPointWindowName());
                console.log(env.event + "  " + HMC.getPointWindowName());
            }
        }
        // console.log(env.event + "  " + HMC.getPointWindowName());

    });
    // 启动
    HMC.Auto.mouseHook.start();

    // 在窗口加载完成后打开开发者工具
    mainWindow.webContents.once('dom-ready', () => {
        // mainWindow.webContents.openDevTools();
        // 读取命令文件
        fs.readFile(path.join(process.cwd(), "command.txt"), "utf8", (err, data) => {
            console.log(data);
            mainWindow.webContents.send('read-command', data);
        })
    });

}


// 当 Electron 完成初始化并准备创建浏览器窗口时，调用 createWindow 函数
app.whenReady().then(createWindow);
